/*
 * This file is part of aKoustiK.

 * aKoustiK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * aKoustiK is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with aKoustiK.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <KGlobal>
#include <KSharedConfig>
#include <KSharedConfigPtr>
#include <KStandardDirs>

#include <QtCore/QDebug>

#include <playlist.h>
#include <storage/xspfstorage.h>

Playlist::Playlist(const QList<Item *> &currentItems, const QString &currentName, QObject *parent)
    : QObject(parent),
    internalItemsList(currentItems),
    playlistName(currentName) {

    qDebug("Playlist: constructor invoked");
}

Playlist::~Playlist() {
    qDebug("Playlist: destructor invoked");
}

int Playlist::size() {
    lock.lockForRead();
    bool empty = internalItemsList.isEmpty();
    int size = internalItemsList.size();
    lock.unlock();
    if (empty) {
        return 0;
    }
    return size;
}

Item* Playlist::at(int index) {
    //qDebug("Playlist::at(%i), playlist size: %i", index, size());
    Item* item;
    lock.lockForRead();
    if (internalItemsList.isEmpty()) {
        item = 0;
    }
    else {
        item = internalItemsList.at(index);
    }
    lock.unlock();
    return item;
}

bool Playlist::isEmpty() {
    lock.lockForRead();
    bool empty = internalItemsList.isEmpty();
    lock.unlock();
    return empty;
}

int Playlist::indexOf(Item *item) {
    lock.lockForRead();
    int result = internalItemsList.indexOf(item);
    lock.unlock();
    emit playlistChanged();
    return result;
}

void Playlist::removeItem(int index) {
    qDebug("Playlist: removeItem(%i)", index);
    lock.lockForWrite();
    Item* item = internalItemsList.takeAt(index);
    lock.unlock();
    emit removingItem(index, item);
    emit playlistChanged();
    delete item;
}

void Playlist::appendItems(const QList<Item*> items) {
    qDebug("Playlist: appending %i items...", items.size());
    lock.lockForWrite();
    internalItemsList.append(items);
    lock.unlock();
    emit playlistChanged();
}

const QString& Playlist::name() const {
    return playlistName;
}

void Playlist::setName(const QString &value) {
    playlistName = value;
}

QList<Item*> Playlist::items() {
    lock.lockForRead();
    QList<Item*> copy(internalItemsList);
    lock.unlock();
    return copy;
}
